import axios from 'axios'
import jsonpAdapter from 'axios-jsonp'
export default {
  uid: '0',
  checkplatform: function checkplatform () {
    var uaCase = navigator.userAgent.toLowerCase()
    if (uaCase.indexOf('micromessenger') >= 0) {
      return 'weixin'
    } else if (uaCase.indexOf('360chespeed') >= 0) {
      return 'speedApp'
    } else if (uaCase.indexOf('360che') >= 0) {
      return 'app'
    } else {
      return 'm'
    }
  },
  checkIOS: function checkIOS () {
    let UA = navigator.userAgent
    if (!(/android/i).test(UA)) {
      return true
    }
  },
  ToLogin: function ToLogin () {
    var platform = this.checkplatform()
    switch (platform) {
      case 'weixin':
        if (!this.uid) {
          window.truckhomeAccountBinding.show()
        } else {
          // 解决 微信解绑卡家账号后，用户登录微信的是弹提：请登录
          this.removeCookie('AbcfN_ajaxuid')
          axios({
            url: `https://sso.360che.com/index.php?c=weChatOauthUrl&m=getBindStatus`,
            adapter: jsonpAdapter,
            withCredentials: true
          }).then(res => {
            if (res.data.status === 'err') {
              window.truckhomeAccountBinding.BindStatus = false
              window.truckhomeAccountBinding.mode = 'binding'
              window.truckhomeAccountBinding.onInputHandle()
            }
            window.truckhomeAccountBinding.show()
          }).catch((res) => {
            this.showErrorInfo('网络错误')
          })
        }
        break
      case 'app':
        let time = setInterval(function () {
          if (window.WebViewJavascriptBridge) {
            clearInterval(time)
            window.WebViewJavascriptBridge.callHandler('onLogin', {})
          };
        }, 50)
        break
      case 'm':
        location.href = `https://sso.360che.com/index.php?referer=${
          window.location.href}`
        break
      case 'speedApp':
        this.callNativeMethod('onLogin', {})
        break
    }
  },
  init: function init () {
    let platform = this.checkplatform()
    switch (platform) {
      case 'weixin':
        if (!window.define && !window.jQuery) {
          var tjs = document.createElement('script')
          tjs.src = 'https://s.kcimg.cn/public/m/js/t.min.js'
          document.body.appendChild(tjs)
        }
        if (!window.truckhomeAccountBinding) {
          var binding = document.createElement('script')
          binding.src = 'https://s.kcimg.cn/public/wechat/wechat.accout.binding.2.0.4.min.js'
          binding.charset = 'utf-8'
          document.body.appendChild(binding)
        }
        this.checkLogin()
        break
      case 'm':
        this.checkLogin()
        break
      case 'app':
        this.appGetUid()
        break
      case 'speedApp':
        this.appGetUid()
        break
    }
  },
  isInclude (name) {
    var js = /js$/i.test(name)
    var es = document.getElementsByTagName(js ? 'script' : 'link')
    for (var i = 0; i < es.length; i++) { if (es[i][js ? 'src' : 'href'].indexOf(name) !== -1) return true }
    return false
  },
  // 监听app回调
  connectWebViewJavascriptBridge (callback) {
    let isIOS = this.checkIOS()
    let platform = this.checkplatform()
    if (platform === 'speedApp') {
      if (!isIOS) {
        callback()
      } else {
        this.registerIOS(callback)
      }
    } else if (platform === 'app') {
      if (window.WebViewJavascriptBridge) {
        callback(window.WebViewJavascriptBridge)
      } else {
        document.addEventListener(
          'WebViewJavascriptBridgeReady',
          function () {
            callback(window.WebViewJavascriptBridge)
          },
          false
        )
      }
    }
  },
  registerIOS (callback) {
    let timer = setTimeout(() => {
      if (window.WVJBCallbacks) {
        timer && clearTimeout(timer)
        return window.WVJBCallbacks.push(callback)
      }
      window.WVJBCallbacks = [callback]
      var WVJBIframe = document.createElement('iframe')
      WVJBIframe.style.display = 'none'
      WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
      document.documentElement.appendChild(WVJBIframe)
      setTimeout(function () {
        document.documentElement.removeChild(WVJBIframe)
      }, 0)
      timer && clearTimeout(timer)
      this.registerIOS(callback)
    }, 50)
  },
  removeCookie: function (name) {
    document.cookie =
      name +
      '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;' +
      ';path=/;domain=.360che.com'
  },
  checkLogin () {
    // 微信和m获取uid
    var userid = document.cookie.match(/AbcfN_ajaxuid=([^;$]+)/)
    if (userid && userid[1]) {
      this.uid = userid[1]
    } else {
      this.uid = 0
    }
  },
  appGetUid () {
    // app获取uid
    var UA = navigator.userAgent
    var userid = UA.match(/USERID[^\s]+/)[0].substr(7)
    if (userid !== '0') {
      this.uid = userid
    }
  },
  getUid () {
    let time = +new Date()
    axios({
      url: `https://bbs-api.360che.com/interface/app/index.php?action=LoginCheck&type=user&time=${time}`,
      adapter: jsonpAdapter,
      withCredentials: true
    }).then(res => {
      if (!res.data.status) {
        this.uid = res.data.data
      }
    })
  },
  // 调用极速版app方法
  callNativeMethod (method, param, callback) {
    let isIOS = this.checkIOS()
    if (isIOS) {
      const time = setInterval(function () {
        if (window.WebViewJavascriptBridge) {
          window.WebViewJavascriptBridge.callHandler(method, param, callback)
          clearInterval(time)
        }
      }, 50)
    } else {
      try {
        if (JSON.stringify(param) === '{}' || !param) {
          // eslint-disable-next-line
          thSpeed[method]()
        } else {
          // eslint-disable-next-line
          thSpeed[method](typeof param === 'object' ? JSON.stringify(param) : param)
        }
      } catch (e) {
        // console.log(e)
      }
    }
  }
}
// Trucklogin.init()
// exports.default = Trucklogin
